/**
 * 处理表格数据的工具函数
 */
import * as XLSX from 'xlsx';

// 读取表格文件所有内容
 function readXLSXFile(file,sheetName){
    return new Promise(async (resolve, reject) => {
       try {
         let result = await (await fetch(file)).arrayBuffer();
        result = new Uint8Array(result);
        const workbook = XLSX.read(result, { type: 'array' });
        // console.log('Workbook:', workbook);
        if(sheetName)  {
            // 如果指定了sheetName，则读取指定的工作表
            const worksheet = workbook.Sheets[sheetName];
            if (!worksheet) {
                throw new Error(`Sheet "${sheetName}" not found in the workbook.`);
            }
            const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            // console.log('Data from sheet:', sheetName, data);
            resolve(data);
        } else{
            // 如果没有指定sheetName，则读取全部工作表
            const allData = workbook.SheetNames.map(sheet => {
                const ws = workbook.Sheets[sheet];
                return XLSX.utils.sheet_to_json(ws, { header: 1 });
            }); 
            // console.log('Data from all sheets:', allData);
            resolve(allData);
        }
       } catch (error) {
        console.log(error);
        reject(error);
       }
    });
}

function getSheetData(workbook, sheetName) {
    const worksheet = workbook.Sheets[sheetName];
    if (!worksheet) {
        throw new Error(`Sheet "${sheetName}" not found in the workbook.`);
    }
    return XLSX.utils.sheet_to_json(worksheet, { header: 1 });
}

function getAllSheetNames(workbook) {
    return workbook.SheetNames;
}

function getSheetNames(workbook) {
    return workbook.SheetNames.map((name) => ({
        name,
        data: XLSX.utils.sheet_to_json(workbook.Sheets[name], { header: 1 }),
    }));
}
// 将json导出成excel表格
function writeXLSXFile(data, fileName,sheetName = 'Sheet1') {
    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
    XLSX.writeFile(workbook, fileName);
}

export {
    readXLSXFile,
    getSheetData,
    getAllSheetNames,
    getSheetNames,
    writeXLSXFile
};